

const KeyLenth = 128;
class KeyInput{
    constructor(gameApp) {
        this._gameApp = gameApp;
        let canvas = gameApp.canvas;

        // 记录上一帧出现过的键盘事件
        this.lstKeys = [];
        this.lstLast = [];
        for(let i = 0; i < KeyLenth;++i){
            this.lstLast[i] = this.lstKeys[i] = false;
        }

        canvas.addEventListener('keydown',this._onKeyDown.bind(this),false);
        canvas.addEventListener('keyup',this._onKeyUp.bind(this),false);
    }

    _onKeyDown(e){
        let keycode = e.keyCode;
        if(keycode < KeyLenth && keycode >= 0 ){
            this.lstLast[keycode] = true;
        }
    }
    _onKeyUp(e){
        let keycode = e.keyCode;
        if(keycode < KeyLenth && keycode >= 0 ){
            this.lstLast[keycode] = false;
        }
    }

    //--------------------------
    // apis
    isKeyDown(key){
        return this.lstKeys[key];
    }

    isKeyFirstDown(key){
        return this.lstKeys[key] && !this.lstLast[key];
    }

    isKeyUp(key){
        return !this.lstKeys[key] && this.lstLast[key];
    }

    /**
     * 循环中,检查输入之前调用
     * @example
     *  keyInput.pollEvents();
     *  keyInput.checkKeyInput();
     */
    pollEvents(){
        for(let i = 0; i < KeyLenth; ++i){
            let pre = this.lstKeys[i];
            this.lstKeys[i] = this.lstLast[i];
            this.lstLast[i] = pre;
        }
    }
}

module.exports = KeyInput;